package com.hgyc.mom.tool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.tool.entity.AutoCodePart;
import com.hgyc.mom.tool.mapper.AutoCodePartMapper;
import com.hgyc.mom.tool.service.AutoCodePartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 编码生成规则组成Service业务层实现
 *
 * @author fwj
 * @since 2025-05-06
 */
@Slf4j
@Service
public class AutoCodePartServiceImpl extends ServiceImpl<AutoCodePartMapper, AutoCodePart> implements AutoCodePartService {

    @Override
    public List<AutoCodePart> getByRuleId(Long ruleId) {
        LambdaQueryWrapper<AutoCodePart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AutoCodePart::getRuleId, ruleId);
        return list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveList(List<AutoCodePart> partList) {
        if (!partList.isEmpty()) {
            Long ruleId = partList.get(0).getRuleId();
            deleteByRuleId(ruleId);

            partList.forEach(part -> {
                //清空临时ID
                part.setId(null);
            });
            saveBatch(partList);
        }
    }

    @Override
    public void deleteBatchByParentIds(List<Long> ids) {
        LambdaQueryWrapper<AutoCodePart> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AutoCodePart::getRuleId, ids);
        remove(wrapper);
    }

    private void deleteByRuleId(Long ruleId) {
        LambdaQueryWrapper<AutoCodePart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AutoCodePart::getRuleId, ruleId);
        remove(queryWrapper);
    }
}
